<template>
	<el-container>
		<!-- 顶栏 -->
		<el-header style="padding: 0;">
			<headerBar :title="getTitle()" :routeBack="() => { }" :flash="nwStore.increment" />
		</el-header>
		<!-- 展示栏 -->
		<el-main style="background-color: #f7f7f7;">
			<epubVue v-if="ext === 'epub'"></epubVue>
			<div :key="nwStore.count" v-else style="height: 80vh;word-wrap: break-word;white-space: pre-wrap;">
				{{ text }}
			</div>
		</el-main>
		<el-footer style="padding: 0;">
			<footerBar />
		</el-footer>
	</el-container>

</template>

<script setup lang="ts">
import headerBar from '@/components/ToolHeaderBar.vue'
import epubVue from './NWEpubVue.vue'
import footerBar from './NWFooterBar.vue'
import { onMounted, onBeforeUnmount, watch, ref } from 'vue';
import { ElMessage, ElNotification } from 'element-plus'
import { useBaseStore } from '@/stores/baseStore';
import { useNWStore } from '@/stores/nwStore'
import { useRoute } from 'vue-router';
import axios from 'axios';

const baseStore = useBaseStore();
const nwStore = useNWStore();
const route = useRoute();

baseStore.showContent = 'novelWatcher';

nwStore.prop.nid = route.params.nid
nwStore.prop.chapterName = route.params.chapterName
if (nwStore.prop.nid === 'local')
	nwStore.prop.chapterName = nwStore.prop.chapterName.replaceAll('|', '/');


const text = ref(nwStore.prop.chapterName + '\n等待内容获取...')
const chapterName = nwStore.prop.chapterName;
const ext = chapterName.substring(chapterName.lastIndexOf('.') + 1);



onMounted(
	async () => {

		if (nwStore.prop.nid !== 'local') {
			await getNovel()
		} else {
			nwStore.novel = {
				name: '本地阅读',
			}
		}
		if (ext !== 'epub') {
			ElNotification({
				title: '提示',
				type: 'info',
				showClose: true,
				offset: 50,
				message: "当前文件格式为 \'" + ext + "\' , 非默认格式 \'epub\' , 出现解析异常请反馈！！！"
			})
			getText()
		}
		nwStore.loadPersistedData()

	}
)

watch(
	() => nwStore.count,
	() => {
		getNovel()
		if (ext !== 'epub') {
			getText()
		}
	});

const getNovel = async () => {
	try {
		const result = await axios.get('/api/novel/' + nwStore.prop.nid)
		if (result.data.code === 200) {
			nwStore.novel = result.data.data[0];
			console.log("获取小说信息");
			console.log(nwStore.novel);
		}
	} catch (error) {
		ElMessage.error({
			showClose: true,
			message: "获取小说信息失败！！！"
		})
		console.log(error);
	}
}

const getTitle = () => {
	if (nwStore.prop.nid !== 'local')
		return (nwStore.novel?.name || '小说名称') + ' - ' + nwStore.prop.chapterName.split('.')[0]
	else
		return '本地阅读 - ' + nwStore.prop.chapterName.split('/').pop().split('.')[0]
}

const getText = async () => {
	const url = nwStore.novel?.src + nwStore.prop.chapterName
	console.log(url);

	const result = await axios.get(url);
	text.value = result.data;
}


</script>
